using System;
using System.Windows;
using System.Windows.Threading;
using System.Windows.Input;
using System.Runtime.InteropServices;

namespace WaistGuard
{
    public partial class RestWindow : Window
    {
        private DispatcherTimer? timer;
        private TimeSpan remainingTime;
        public event EventHandler? RestCompleted;

        public static string[] DefaultTips { get; set; } = new[]
        {
            "长时间的疲劳容易导致错误和失误，所以请务必注意休息，让身体和精神都得到放松，避免不必要的压力和紧张。",
            "亲爱的，你的努力我看在眼里，但请别让工作影响了你的身体和心情。记得休息一下，让疲惫的身心得到放松。",
            "没有什么比健康的身体和愉快的心情更重要了。所以，请放下手头的工作，让自己休息一下，享受片刻的宁静。",
            "别让疲惫埋没了你的笑容，休息是为了更好地奋斗！"
        };

        private int currentTipIndex = 0;
        private DispatcherTimer? tipsTimer;

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
        private static LowLevelKeyboardProc _proc = HookCallback;
        private static IntPtr _hookID = IntPtr.Zero;

        private const int WH_KEYBOARD_LL = 13;

        private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0)
            {
                return (IntPtr)1; // 屏蔽所有键盘输入
            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }

        public RestWindow(int restMinutes)
        {
            InitializeComponent();
            
            remainingTime = TimeSpan.FromMinutes(restMinutes);
            UpdateCountdownDisplay();

            timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(1)
            };
            timer.Tick += Timer_Tick;
            timer.Start();

            tipsTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(5)
            };
            tipsTimer.Tick += TipsTimer_Tick;
            tipsTimer.Start();

            TipsText.Text = DefaultTips[0];

            // 安装键盘钩子
            _hookID = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, IntPtr.Zero, 0);
            
            this.Closed += (s, e) => 
            {
                // 移除键盘钩子
                if (_hookID != IntPtr.Zero)
                {
                    UnhookWindowsHookEx(_hookID);
                    _hookID = IntPtr.Zero;
                }
            };
        }

        private void Timer_Tick(object? sender, EventArgs e)
        {
            remainingTime = remainingTime.Subtract(TimeSpan.FromSeconds(1));
            
            if (remainingTime.TotalSeconds <= 0)
            {
                timer?.Stop();
                // 移除键盘钩子
                if (_hookID != IntPtr.Zero)
                {
                    UnhookWindowsHookEx(_hookID);
                    _hookID = IntPtr.Zero;
                }
                RestCompleted?.Invoke(this, EventArgs.Empty);
                this.Close();
                return;
            }

            UpdateCountdownDisplay();
        }

        private void UpdateCountdownDisplay()
        {
            CountdownLabel.Content = $"{remainingTime.Minutes:D2}:{remainingTime.Seconds:D2}";
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            
            // 禁用窗口的关闭按钮
            var hwnd = new System.Windows.Interop.WindowInteropHelper(this).Handle;
            var style = NativeMethods.GetWindowLong(hwnd, NativeMethods.GWL_STYLE);
            style &= ~NativeMethods.WS_SYSMENU;
            NativeMethods.SetWindowLong(hwnd, NativeMethods.GWL_STYLE, style);
        }

        private void TipsTimer_Tick(object? sender, EventArgs e)
        {
            currentTipIndex = (currentTipIndex + 1) % DefaultTips.Length;
            TipsText.Text = DefaultTips[currentTipIndex];
        }

        private void StopButton_Click(object sender, RoutedEventArgs e)
        {
            timer?.Stop();
            // 移除键盘钩子
            if (_hookID != IntPtr.Zero)
            {
                UnhookWindowsHookEx(_hookID);
                _hookID = IntPtr.Zero;
            }
            RestCompleted?.Invoke(this, EventArgs.Empty);
            this.Close();
        }
    }
}

// 添加 Win32 API 调用
internal static class NativeMethods
{
    public const int GWL_STYLE = -16;
    public const int WS_SYSMENU = 0x80000;

    [DllImport("user32.dll", SetLastError = true)]
    public static extern int GetWindowLong(IntPtr hWnd, int nIndex);

    [DllImport("user32.dll")]
    public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
} 